package gof_002_结构型_Structural.gof_001_代理_Proxy.gof_003_DynamicProxy.g_2_cglib;

/**
 * 在 IntelliJ IDEA 中手动添加依赖包 cglib
 * 如果是 SpringBoot 项目会自动集成  cglib,可以使用框架自带的 cglib
 */
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;


/**
 * 经纪人
 */
public class Agent implements MethodInterceptor {
    private Object obj;

    public Agent(Object obj) {
        this.obj = obj;
    }

    public Object getProxyObj(Class clazz){
        //创建代理类
        Object proxyObj = Enhancer.create(clazz, this);
        return proxyObj;
    }

    /**
     * 经纪人的杂活累活
     */
    private void connection() {
        System.out.println("经纪人在联系...");
    }

    private void bargain() {
        System.out.println("经纪人在讨价还价...");
    }

    private void payEarnestMoney() {
        System.out.println("经纪人在支付订金...");
    }

    private void payBalanceDue() {
        System.out.println("经纪人在支付尾款...");
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        connection();
        bargain();
        payEarnestMoney();

        method.invoke(obj,objects);		//调用具体方法

        payBalanceDue();
        return null;
    }

}